package weaver.batchchanges.cmd;

import com.alibaba.nacos.client.utils.StringUtils;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import weaver.conn.RecordSet;
import weaver.batchchanges.bean.BatchTasksChangesGlobalData;
import weaver.batchchanges.bean.TaskLedgerPhase2Bean;
import weaver.batchchanges.util.DataConvertUtil;

import java.util.*;

/**
 * 修改任务台账二期表数据的Cmd
 */
public class UpdateTaskLedgerPhase2DataCmd extends AbstractCommonCommand<List<TaskLedgerPhase2Bean>> {


    public UpdateTaskLedgerPhase2DataCmd(TaskLedgerPhase2Bean taskLedgerPhase2Bean) {
        params = new HashMap<>();
        params.put("dataList", new ArrayList<TaskLedgerPhase2Bean>() {{
            add(taskLedgerPhase2Bean);
        }});
    }

    public UpdateTaskLedgerPhase2DataCmd(List<TaskLedgerPhase2Bean> taskLedgerPhase2Beans) {
        params = new HashMap<>();
        params.put("dataList", taskLedgerPhase2Beans);
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public List<TaskLedgerPhase2Bean> execute(CommandContext commandContext) {
        RecordSet rs = new RecordSet();
        StringBuilder sql = new StringBuilder();
        List<TaskLedgerPhase2Bean> dataList = (List<TaskLedgerPhase2Bean>) params.get("dataList");
        List<Object> values = new ArrayList<>();

        //存放执行失败的数据
        List<TaskLedgerPhase2Bean> failureList = new ArrayList<>();

        //遍历并update每条数据
        dataList.forEach(taskLedgerPhase2Bean -> {
            Map<String, Object> map = DataConvertUtil.convertToMap(taskLedgerPhase2Bean);
            sql.append("update " + BatchTasksChangesGlobalData.TASK_LEDGER_PHASE2_TABLE_NAME + " SET ");

            Set<String> keySet = map.keySet();
            keySet.forEach(key -> {
                if (StringUtils.isNotEmpty(key) && !key.equals("touchpointbh") && !key.equals("id") && map.get(key) != null) {
                    sql.append(key + " = ? ,");
                    values.add(map.get(key));
                }
            });
            //拼接需要更新数据的id
            sql.deleteCharAt(sql.length() - 1).append(" where id = " + taskLedgerPhase2Bean.getId() + ";");
            boolean isSuccess = rs.executeUpdate(sql.toString(), values.toArray());
            if (!isSuccess) {
                failureList.add(taskLedgerPhase2Bean);
            }
        });

        return failureList;
    }


}
